package com.ddz.library.bitmap

import android.content.ContentValues
import android.content.Intent
import android.graphics.*
import android.provider.MediaStore
import android.provider.MediaStore.MediaColumns
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import android.text.format.DateUtils
import com.ddz.library.JKLibrary
import com.ddz.library.log.JKLog
import java.io.OutputStream
import kotlin.math.round

object JKBitmapUtils {
    /**
     * Android 高斯模糊方案
     * @param scale 0.0-1.0
     * @param blurRadius 0.0-25.0 模糊角度
     */
    @JvmStatic
    fun blurBitmap(bitmap: Bitmap, scale: Float, blurRadius: Float, foregroundColor: Int? = null): Bitmap {
        val width = round(bitmap.width * scale).toInt()
        val height = round(bitmap.height * scale).toInt()
        val inputBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false)
        if (foregroundColor != null) {
            val canvas = Canvas(inputBitmap)
            val paint = Paint()
            paint.style = Paint.Style.FILL
            paint.color = foregroundColor
            canvas.drawRect(Rect(0, 0, width, height), paint)
            canvas.save()
        }
        val outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val renderScript = RenderScript.create(JKLibrary.context)
        val blurScript = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript))
        val tmpIn = Allocation.createFromBitmap(renderScript, inputBitmap)
        val tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap)
        blurScript.setRadius(blurRadius)
        blurScript.setInput(tmpIn)
        blurScript.forEach(tmpOut)
        tmpOut.copyTo(outputBitmap)
        return outputBitmap
    }

    fun saveToGallery(bitmap: Bitmap, name: String?):Boolean {
        val timeMillis = System.currentTimeMillis()
        val contentValue = ContentValues()
        contentValue.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        contentValue.put(MediaStore.Images.Media.MIME_TYPE, if (name?.endsWith("png") == true) "image/png" else "image/jpeg")
        contentValue.put(MediaStore.MediaColumns.DATE_ADDED, timeMillis / 1000)
        contentValue.put(MediaStore.MediaColumns.DATE_MODIFIED, timeMillis / 1000)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            contentValue.put(MediaStore.MediaColumns.DATE_EXPIRES, (timeMillis + DateUtils.DAY_IN_MILLIS) / 1000)
            contentValue.put(MediaStore.MediaColumns.IS_PENDING, 1)
        }
        val resolver = JKLibrary.context!!.contentResolver
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValue)
        if (uri == null){
            JKLog.e("图片保存到本地","saveToGallery 错误")
            return false
        }
        JKLibrary.context!!.grantUriPermission(JKLibrary.context!!.packageName,uri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        var outputStream:OutputStream? = null
        var isSuccess = true
        try {
            outputStream = resolver.openOutputStream(uri)
            if (outputStream != null) {
                bitmap.compress(if (name?.endsWith("png") == true) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, 100,outputStream)
                contentValue.clear()
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    contentValue.put(MediaStore.MediaColumns.IS_PENDING, 0)
                    contentValue.putNull(MediaColumns.DATE_EXPIRES)
                }
                resolver.update(uri,contentValue,null,null)
            }
        }catch (e:Exception){
            resolver.delete(uri,null,null)
            e.printStackTrace()
            isSuccess = false
        }finally {
            outputStream?.close()
        }
        return isSuccess
    }
}